<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>event</title>
    <style type="text/css">

    </style>
</head>
<body>


<h2>1、事件绑定</h2>
<input type="button" id="btn1" value="clickMe">
<input type="button" id="btn2" value="clickMe">


<script>
window.onload = function(){


    // 如果用onclick给btn绑定事件，
    // btn.onclick = function(){console.log("a");}
    // btn.onclick = function(){console.log("b");}
    // 最终只会输出b
    // 如果希望两个绑定事件都有效，那么使用attachEvent / addEventListener

    // IE7-8 :          attachEvent('onclick', 函数)
    // IE7-8 :          detachEvent('onclick', 函数)

    // Chrom FF IE9-10: addEventListener('click', 函数, 捕获)
    // Chrom FF IE9-10: removeEventListener('onclick', 函数, 捕获)

    var btn1 = document.getElementById("btn1");

    if(btn1.attachEvent){
        // 执行顺序： b,a
        btn1.attachEvent('onclick', function(){
            console.log("a");
        });
        btn1.attachEvent('onclick', function(){
            console.log("b");
        });
    }

    else{
        // 执行顺序： a,b
        btn1.addEventListener('click', function(){
            console.log("a");
        }, false);
        btn1.addEventListener('click', function(){
            console.log("b");
        }, false);
    }


    // 给上述的兼容写法封装成一个函数：myAddEvent
    var btn2 = document.getElementById("btn2");
    myAddEvent(btn2, "click", function(){
        console.log("aa");
    });
    myAddEvent(btn2, "click", function(){
        console.log("bb");
    });

}


function myAddEvent(obj, ev, fn){
    if(obj.attachEvent){
        obj.attachEvent('on'+ev, fn);
    }
    else{
        obj.addEventListener(ev, fn, false)
    }
}


</script>
</body>
</html>